#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tunnel.h"
#include "strfix.h"
/*
 * Request:
 * tunnel: 10
 * method: 1
 * active: 1
 * number: 2000
 *
 * Response:
 * tunnel: 10
 *
 * */

int tunl_set_req(char *buf, tunl_t *t)
{
    sprintf(buf, "tunnel: %s\n" "active: %d\n" "number: %d\n" "\n", \
            TUNL_VERSION, t->active, t->number);
    // printf("[%s]\n", buf);
    return strlen(buf);
}

int tunl_get_req(char *buf, int len, tunl_t *t)
{
    char val[64] = {0};
    char *p = buf;

    t->is_got_req = 0;

    buf[len] = '\0';

    if (len < 2)
        return -1;

    if (buf[len-1] != '\n' || buf[len-2] != '\n')
        return -2;

    // protocol
    p = strbtwn(p, "tunnel: ", "\n", val);
    if (p == NULL || strcmp(val, TUNL_VERSION) != 0)
        return -3;

    // active
    p = strbtwn(p, "active: ", "\n", val);
    if (p == NULL || strint(val, &t->active) < 0)
        return -4;

    // number
    p = strbtwn(p, "number: ", "\n", val);
    if (p == NULL || strint(val, &t->number) < 0)
        return -5;

    t->is_got_req = 1;
    return 0;
}

int tunl_set_res(char *buf, tunl_t *t)
{
    sprintf(buf, "tunlres: %s\n" "\n", TUNL_RES_GO);
    return strlen(buf);
}

int tunl_get_res(char *buf, int len, tunl_t *t)
{
    static char val[64] = {0};
    char *p = buf;

    buf[len] = '\0';

    if (len < 2)
        return -1;

    if (buf[len-1] != '\n' || buf[len-2] != '\n')
        return -2;

    p = strbtwn(p, "tunlres: ", "\n\n", val);
    if (p == NULL || strcmp(val, TUNL_RES_GO) != 0)
        return -3;

    return 0;
}
